/**
 * 监听元素尺寸变化，不是浏览器尺寸变化。
 * demo: v-resize:debounce.300="handler"
 */
import { debounce } from 'lodash-es'

const defaultDelay = 150

function getOptions(modifiers) {
  if (!modifiers) {
    return { delay: defaultDelay, initial: false }
  }
  const { initial = false } = modifiers
  let delay = Object.keys(modifiers)
    .map(k => parseInt(k))
    .find(v => !isNaN(v))
  delay = delay || defaultDelay
  return { delay, initial }
}

function createResizeSensor(el, { value, arg, options }) {
  if (!el.style.position) {
    el.style.position = 'relative'
  }
  let iframe = document.createElement('iframe')
  iframe.className = 'resize-directive'
  iframe.style.cssText = `position: absolute; left: 0; top: 0; width: 100%; height: 100%;border: 0; margin: 0; display: block; z-index: -999;`
  el.appendChild(iframe)

  let callback = () => value(el)
  switch (arg) {
    case 'debounce':
      callback = debounce(() => value(el), options.delay)
      break
    case 'throttle':
      callback = debounce(() => value(el), options.delay, { leading: true, trailing: true, maxWait: options.delay })
      break
  }

  ;(iframe.contentWindow || iframe).onresize = callback
}
export default {
  inserted: (el, { value, arg, modifiers }) => {
    if (!value || typeof value !== 'function') {
      console.warn('v-resize should received a function as value')
      return
    }
    const options = getOptions(modifiers)
    createResizeSensor(el, { value, arg, options })

    // 初始就执行一次
    if (options.initial) {
      value(el)
    }
  },
  unbind: el => {
    for (var i = 0, node; (node = el.childNodes[i]); i++) {
      if (node.className === 'resize-directive') {
        el.removeChild(node)
      }
    }
  }
}
